package cn.ccew.sys.web.login;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.ccew.common.utils.MD5;
import cn.ccew.common.utils.ResponseUtils;
import cn.ccew.sys.model.SysPersonnel;
import cn.ccew.sys.web.SysBaseController;

@Controller
public class LoginController extends SysBaseController {

	public static final String curr_user_key = "curr_user_key";

	@RequestMapping("login.wb")
	public String index(HttpServletRequest request) throws Exception {
		SysPersonnel admin = this.getCurrAdmin(request);
		if (null != admin) {
			return "redirect:main.wb";
		}

		return "sys/login/login";
	}

	@RequestMapping("logout.wb")
	public String logout(HttpServletRequest request) throws Exception {
		HttpSession session = request.getSession();
		session.setAttribute(curr_user_key, "");
		return "sys/login/login";
	}

	@RequestMapping(value = "log.wb", method = { RequestMethod.POST })
	public @ResponseBody
	Object login(String userName, String userPass, String code, HttpServletRequest request) throws Exception {
		try {
			userPass=userPass.substring(8, 24);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("userName=" + userName + "  userPass=" + userPass);
		HttpSession session = request.getSession();

		// 验证码错先注掉
		String cookCode = session.getAttribute("code").toString();
		if (!code.equals(cookCode)) {
			return ResponseUtils.sendFailure("验证码错误");
		}

		SysPersonnel admin = null;
		admin = baseService.findObjByProperty("loginName", userName, SysPersonnel.class);

		if (null != admin && userPass.equals(MD5.MD5(admin.getLoginPassword()))) {
			// XXXX do
			session.setAttribute(curr_user_key, admin);
			if (admin.getInfoState() == 0) {
				return ResponseUtils.sendFailure("登录失败,该用户还未启用,请联系管理员");
			}
			if (admin.getInfoState() == 2) {
				return ResponseUtils.sendFailure("登录失败,该用户被锁定,请联系管理员");
			}
			return ResponseUtils.sendSuccess("登录成功");
		}
		return ResponseUtils.sendFailure("登录失败");

	}

	@RequestMapping(value = "doChangePsw.wb", method = RequestMethod.POST)
	public void doChangePsw(HttpServletRequest request, HttpServletResponse response) throws Exception {

		String useid = request.getParameter("id");
		String userpassword = request.getParameter("userpassword");

		try {
			SysPersonnel admin = this.getCurrAdmin(request);
			admin.setLoginPassword(userpassword);
			baseService.saveOrUpdate(admin);
			response.getWriter().print("{success:true,msg:'修改成功'}");
		} catch (Exception e) {
			response.getWriter().print("{success:false,msg:'修改失败'}");
			e.printStackTrace();
		}

	}

	public static String getCurrUserKey() {
		return curr_user_key;
	}

	// 创建验证码
	@RequestMapping(value = "createCode.wb", method = RequestMethod.GET)
	public void createCode(HttpServletRequest request, HttpServletResponse response) throws Exception {

		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0L);
		Random random = new Random();
		int width = 70;
		int height = 25;

		BufferedImage image = new BufferedImage(width, height, 1);
		OutputStream os = response.getOutputStream();

		Graphics g = image.getGraphics();
		g.setColor(getRandColor(200, 250));
		g.fillRect(0, 0, width, height);
		g.setColor(getRandColor(160, 200));

		for (int i = 0; i < 155; i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int xl = random.nextInt(12);
			int yl = random.nextInt(12);
			g.drawLine(x, y, x + xl, y + yl);
		}

		String base = "abcdefghijkhnmpqrstuvwxyz123456789";
		int length = base.length();
		String[] fontTypes = { "u5b8bu4f53", "u65b0u5b8bu4f53", "u9ed1u4f53", "u6977u4f53", "u96b6u4e66" };
		String content = "";

		for (int i = 0; i < 5; i++) {
			int start = random.nextInt(length);
			String rand = base.substring(start, start + 1);
			content = content + rand;
			g.setColor(getRandColor(10, 150));
			g.setFont(new Font(fontTypes[random.nextInt(fontTypes.length)], 1, 14 + random.nextInt(4)));
			g.drawString(rand, 15 * i, 20);
		}
		g.dispose();
		HttpSession session = request.getSession();
		session.setAttribute("code", content);
		ImageIO.write(image, "JPEG", os);
		os.close();
	}

	private Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}

}
